package com.yanqu.backendweb.intercept;
import com.yanqu.backendweb.utils.CustomResponse;
import com.yanqu.backendweb.utils.Response;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.Map;

/**
 * @author duli
 * @version 1.0
 * @date 2020/22/01 11:44
 * @Description
 */
@ControllerAdvice
public class ResponseIntercept implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        if (body == null) {
            return Response.success();
        }
        if (body instanceof CustomResponse) {
            return ((CustomResponse) body).getResponse();
        }
        if (body instanceof Response || body instanceof String) {
            return body;
        }
        if (body instanceof Map && ((Map) body).containsKey("status")) {
            return body;
        }
        return Response.success(body);
    }


}
